import datetime
import shutil
from uuid import uuid1

from flask import current_app, Blueprint
from werkzeug.utils import safe_join

from ...common import helper
from ...extensions import tc, db
from ...models import TransferModel, TransferSchema

transfer_bp = Blueprint('Transfer', __name__, url_prefix='/api/transfer')


@transfer_bp.route("/", methods=['POST'])
def transfer__add_record():
    """

    添加一条传输记录

    :return:

    """
    uid = str(uuid1())
    code = tc.set_token(uid)  # 设置简码保存
    db.session.add(
        TransferModel(
            id=uid,
            create_at=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            code=code
        )
    )
    db.session.commit()
    return helper.success(data=uid)


@transfer_bp.route("/<t_id>", methods=['GET'])
def transfer__get_record(t_id):
    """

    获取指定id的传输记录

    :param t_id:
    :return:

    """
    query = TransferModel.query.get(t_id)
    return helper.success(data=TransferSchema().dump(query))


@transfer_bp.route("/<t_id>", methods=['DELETE'])
def transfer__delete_record(t_id):
    upload_path = current_app.config['UPLOAD_FOLDER']
    query: TransferModel = TransferModel.query.filter_by(id=t_id).first()
    shutil.rmtree(safe_join(upload_path, query.id))
    db.session.delete(query)
    db.session.commit()
    return helper.success()
